/*
 * Semaphore Demo
 * Liu Jinzhu
 * 2018-04-10
 */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

void *thread_function(void *arg);

int main() {

    int res;                			// 保存线程创建返回值
    pthread_t a_thread;    			// 保存线程标识信息
    void *thread_result;   	 		// 线程运行返回值

    res = pthread_create(&a_thread, NULL, thread_function, NULL);
    if (0 != res) {
        perror("线程创建失败\n");
        exit(EXIT_FAILURE);
     }

    sleep(3);

    printf("取消线程...\n");
    res = pthread_cancel(a_thread);

    printf("等待线程结束...\n");
    res = pthread_join(a_thread, &thread_result);
    if (0 != res) {
        perror("等待线程结束失败\n");
        exit(EXIT_FAILURE);
    }
    printf("线程已结束\n");

    exit(EXIT_SUCCESS);
}

void *thread_function(void *arg) {
	int i, res;
	res = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
	if (0 != res) {
		perror("设置线程取消状态失败\n");
	   exit(EXIT_FAILURE);
	}

	res = pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL); // 采取一些动作后再结束
	if (0 != res) {
		perror("定义线程结束失败\n");
	   exit(EXIT_FAILURE);
	}

	printf("线程函数正在运行\n");
	for (i = 0; i < 10; ++i) {
		printf("线程函数正在运行(%d)...\n", i);
		sleep(1);
	}

   pthread_exit(0);
}

